package com.c.ctgproject.ui.collect

import android.app.AlertDialog
import android.content.Intent
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.view.View
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityPreInputCarInfoBinding
import com.c.ctgproject.entity.guang.UseVinGetCarModelEntity
import com.c.ctgproject.enum.DictionaryMenuEnum
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.http.MyObserverJustOk
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.dialog.MyBottomDialog
import org.jetbrains.anko.startActivity
import org.json.JSONObject

/**
 *作者:LiBW
 *创建日期: 2021/9/7
 *描述:车辆信息预录入 页面 车辆信息录入 页面
 */
class PreInputCarInfoActivity : BaseActivityV2() {
    private val mBinding by lazy { ActivityPreInputCarInfoBinding.inflate(layoutInflater) }

    override fun getLayout() = mBinding.root

    override fun event() {
        mBinding.carVinET.filters = arrayOf<InputFilter>(InputFilter.AllCaps(), InputFilter.LengthFilter(17))
        mBinding.carVinET.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, start: Int, before: Int, count: Int) {
//                mBinding.carVinET.removeTextChangedListener(this)
//                mBinding.carVinET.textSet(p0.toString().toUpperCase())
//                mBinding.carVinET.setSelection(p0.toString().length)
//                mBinding.carVinET.addTextChangedListener(this)
            }

            override fun afterTextChanged(s: Editable?) {
                if (s.toString().length == 17) {
                    checkVinPlate()
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.useVinGetCarModel(s.toString()), MyObserverJustOk(this@PreInputCarInfoActivity) {
                        MyLog.d("回调:$it")
                        val data = getGson().fromJson(it, UseVinGetCarModelEntity::class.java).data
                        data?.description?.let { bean ->
                            mBinding.carModelET.textSet(bean)
                        }
                    })
                }

            }
        })
        mBinding.carPlateET.filters = arrayOf<InputFilter>(InputFilter.AllCaps(), InputFilter.LengthFilter(8))
        mBinding.carPlateET.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, start: Int, before: Int, count: Int) {
//                mBinding.carPlateET.removeTextChangedListener(this)
//                mBinding.carPlateET.textSet(p0.toString().toUpperCase())
//                mBinding.carPlateET.setSelection(p0.toString().length)
//                mBinding.carPlateET.addTextChangedListener(this)
            }

            override fun afterTextChanged(s: Editable?) {
                if (s.toString().length == 7 || s.toString().length == 8) {
                    checkVinPlate()
                }
            }
        })
    }

    private fun checkVinPlate() {
        val vin = mBinding.carVinET.text.handlerNull()
        val plate = mBinding.carPlateET.text.handlerNull()
        if ((plate.length == 7 || plate.length == 8) && vin.length == 17) {
            ApiMethods.apiSubscribe(ApiMethods.retrofit.vinPlateExitsCheck(vin, plate), MyObserverHandlerLoading(this) {
                MyLog.d("回调回调回调:$it")
                val result = JSONObject(it)
                if (result.optInt("data", -1) == 2) {
                    AlertDialog.Builder(this).setTitle("当前车辆信息已存在，您是否重新录入？")
                        .setPositiveButton("继续录入") { _, _ ->
                        }.setNegativeButton("重新录入") { _, _ ->
                            mBinding.carVinET.textSet("")
                            mBinding.carPlateET.textSet("")
                        }.show()
                }
            })
        }
    }


    private fun handlerSingleData() {
        val carVin = mBinding.carVinET.text.handlerNull()
        val carPlate = mBinding.carPlateET.text.handlerNull()
        val carModel = mBinding.carModelET.text.handlerNull()
        val toll = mBinding.tollET.text.handlerNull()
        val status=mBinding.statusSelectET.text.handlerNull()
        val character=mBinding.characterSelectET.text.handlerNull()
        when {
            character.isEmpty() -> {
                showToast("请选择车辆性质")
                mBinding.mCharacterSelectLL.myShake()
            }
            status.isEmpty() -> {
                showToast("请选择车辆状态")
                mBinding.mStatusSelectLL.myShake()
            }
            carFrom.isEmpty() -> {
                showToast("请选择车辆来源(车辆的提交单位)")
                mBinding.mDictionarySelectLL.myShake()
            }
            carVin.isEmpty()&& needVin->{
                showToast("请输入车辆VIN码")
                mBinding.mVinLL.myShake()
            }
//            carVin.length < 17 && needVin-> {
//                showToast("请输入完整的VIN码")
//                mBinding.mVinLL.myShake()
//            }
            carType == 1 && carPlate.isEmpty() -> {
                showToast("请填写车牌")
                mBinding.carPlateLL.myShake()
            }
//            carType != 3 && carSource.isEmpty() -> showToast("请输入车辆来源(车辆的提交单位)")
//            carType != 3 && carVin.isEmpty() -> showToast("请输入车辆VIN码")
//            carType == 3 && carNum.isEmpty() -> showToast("请输入数量")
//            carType == 3 && purchaseWeight.isEmpty() -> showToast("请输入过磅重量")
//            carType == 3 && purchasePoundNo.isEmpty() -> showToast("请输入磅单号")
            else -> {

                val map = HashMap<String, Any>()
                map["carType"] = carType
                //外包车只记录 数量重量 磅单
                map["carSource"] = carFrom
                map["carVin"] = carVin
                map["carPlate"] = carPlate
                map["carModel"] = carModel
                map["toll"] = toll
                map["preRemark"] = mBinding.mRemarkET.text.handlerNull()
                map["carStatus"] = carStatus


                if(!isFastDoubleClick()){
                    if(needVin&&carVin.length < 17){
                        commonDialog("输入的vin码小于17位，是否继续提交"){
                            ApiMethods.apiSubscribe(ApiMethods.retrofit.inputCarInfoSingle(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                                MyLog.d("提交回调:$it")
                                showToast("提交成功")
                                finish()
                            })
                        }
                    }else{
                        ApiMethods.apiSubscribe(ApiMethods.retrofit.inputCarInfoSingle(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                            MyLog.d("提交回调:$it")
                            showToast("提交成功")
                            finish()
                        })
                    }

                }

            }
        }
    }

    //车辆性质 （1-社会车 2-试验车 3-外包车 4-五类车 5-农机具）
    private var carType = 1

    //车辆状态 1-整车 2-车架
    private var carStatus = 1
    private var carFrom = ""
    override fun click() {
        //我的录入
        mBinding.mMyInputTV.setOnClickListener {
            startActivity<MyInputActivity>()
        }

        //选择来源 (供应商)
        mBinding.mDictionarySelectLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.SUPPLIER.menuCode, true, arrayListOf(carFrom))
        }
        //社会车
//        mBinding.mSH.setOnClickListener {
//            carType = 1
//            mBinding.mPlateStartTV.visibility = View.VISIBLE
//            handlerVinStart()
//        }
//        //试验车
//        mBinding.mSY.setOnClickListener {
//            carType = 2
//            mBinding.mPlateStartTV.visibility = View.GONE
//            handlerVinStart()
//        }
//        //外包车
//        mBinding.mWB.setOnClickListener {
//            carType = 3
//            mBinding.mPlateStartTV.visibility = View.GONE
//            handlerVinStart()
//        }
//        //五类车
//        mBinding.mWLC.setOnClickListener {
//            carType = 4
//            mBinding.mPlateStartTV.visibility = View.GONE
//            handlerVinStart()
//        }
//        //五类车
//        mBinding.mNJJ.setOnClickListener {
//            carType = 5
//            mBinding.mPlateStartTV.visibility = View.GONE
//            handlerVinStart()
//        }
        //整车
//        mBinding.mAllCar.setOnClickListener {
//            carStatus = 1
//            handlerVinStart()
//        }
//        //车架
//        mBinding.mUnAllCar.setOnClickListener {
//            carStatus = 2
//            handlerVinStart()
//        }
        //提交
        mBinding.mConfirmBTN.setOnClickListener {
            handlerSingleData()
        }
        //车辆性质
        mBinding.mCharacterSelectLL.setOnClickListener {
            val list=mutableListOf("社会车", "试验车", "外包车","五类车","农机具")
            val dialog = MyBottomDialog.Builder(this).setOnOptionSelectedListener {position->
                mBinding.characterSelectET.text=list[position]
                if(position==0){
                    mBinding.mPlateStartTV.visibility = View.VISIBLE
                }else{
                    mBinding.mPlateStartTV.visibility = View.GONE
                }
                carType=position+1
                handlerVinStart()
            }.setOptions(list).create()
            dialog.show()
        }
        mBinding.mStatusSelectLL.setOnClickListener {
            val list=mutableListOf("整车", "车架")
            val dialog = MyBottomDialog.Builder(this).setOnOptionSelectedListener {position->
                mBinding.statusSelectET.text=list[position]
                carStatus=position+1
                handlerVinStart()
            }.setOptions(list).create()
            dialog.show()
        }
    }

    //VIN码是否必填
    private var needVin = true
    private fun handlerVinStart() {
        if (carStatus == 2) {
            mBinding.mVinStart.visibility = View.INVISIBLE
            needVin = false
        } else {
            if (carType == 1 || carType == 3) {
                mBinding.mVinStart.visibility = View.VISIBLE
                needVin = true
            } else {
                mBinding.mVinStart.visibility = View.INVISIBLE
                needVin = false
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let { result ->
            //字典回调
            if (requestCode == 1000) {
                val name = result.getStringExtra(MyConstants.NAME)
//                val abbreviation=result.getStringExtra(MyConstants.ABBREVIATION)
                carFrom = name.handlerNull()
                mBinding.carSourceET.text = name.handlerNull()
            }
        }
    }
}